const express = require('express')
const bodyParser = require('body-parser')
const path = require('path')
const fs = require('fs')
const cors = require('cors')
const User = require('./user.js')
const { finishQuestion, getAllScore, clearUser } = require('./game.js')

const appDirectory = fs.realpathSync(process.cwd())
const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath)

const app = express()
const PORT = 8889

app.use(bodyParser.json())
app.use(express.static(resolveApp('./')))

// 用户登录
app.post('/loginUser', (req, res) => {
  const loginStatus = User.loginUser(req.body?.username)
  if (loginStatus) {
    console.log('登录用户：', req.body?.username)
    res.send({
      success: true,
      message: '登录成功！'
    })
  } else {
    res.send({
      success: false,
      message: '登录失败，用户名重复！'
    })
  }
})

// 用户退出登录，则清空数据
app.post('/exitUser', (req, res) => {
  const name = req.body?.username
  User.exitUser(name)
  clearUser(name)
  res.send({
    success: true
  })
})

// 完成题目
app.post('/finishQuestion', (req, res) => {
  const { username, level, id } = req.body
  const status = finishQuestion({ username, level, id })
  res.send({
    success: status,
    message: status ? '提交成功！' : '存在相同题目'
  })
})

// 获取所有分数
app.get('/getAllScore', (req, res) => {
  const score = getAllScore()
  res.send({
    success: true,
    message: '提交成功！',
    score
  })
})

app.get('/', (req, res) => {
  res.sendFile(resolveApp('./index.html'))
})

app.listen(PORT, () => {
  console.log(`Example app listening on port ${PORT}`)
})
